"""
网络请求工具类
"""
import requests
import time
import random
import logging
from typing import Optional
from requests.exceptions import RequestException
from config.settings import USER_AGENT, REQUEST_TIMEOUT, RETRY_TIMES, DELAY_RANGE


class WebUtils:
    """网络请求工具"""

    def __init__(self):
        self.session = requests.Session()
        self.session.headers.update({'User-Agent': USER_AGENT})
        self.logger = logging.getLogger(__name__)

    def get(self, url: str, **kwargs) -> Optional[requests.Response]:
        """发送GET请求"""
        for attempt in range(RETRY_TIMES):
            try:
                response = self.session.get(url, timeout=REQUEST_TIMEOUT, **kwargs)
                response.raise_for_status()
                return response

            except RequestException as e:
                self.logger.warning(f"请求失败 (尝试 {attempt + 1}/{RETRY_TIMES}): {e}")
                if attempt < RETRY_TIMES - 1:
                    self.random_delay()

        return None

    def random_delay(self):
        """随机延迟"""
        delay = random.uniform(*DELAY_RANGE)
        time.sleep(delay)

    def close(self):
        """关闭会话"""
        self.session.close()